// @ts-ignore
export default ({ method = 'get', url, params }) => {
  return new Promise((resolve, reject) => {
    const http = new XMLHttpRequest()
    if (method.toLowerCase() === 'get') {
      let arr = []
      for (let key in params) {
        arr.push(key + '=' + params[key])
      }
      url = url + '?' + arr.join('&')
    }
    console.log('即将访问的api:' + url)
    http.open(method, url)

    http.onreadystatechange = () => {
      console.log('http.readyState:' + http.readyState)
      console.log('---------------http-----------------')
      console.log(http)
      console.log(http.status)
      console.log('---------------http end-----------------')
      if (http.readyState === 4) {
        // @ts-ignore
        if (http.status === 200) {
          console.log('开始解析response数据')
          console.log(http.responseText)
          console.log('----------responseText-----------------')
          console.log('----------responseText end-----------------')
          const data = JSON.parse(http.responseText)

          resolve(data)
          console.log('返回成功=======================')
        } else {
          console.log('返回失败')
          const data = JSON.parse(http.responseText)
          console.log(http.responseText)
          resolve(data)
        }
      } else {
        console.log('返回失败')
      }
    }

    if (method.toLowerCase() === 'get') {
      http.send(null)
    } else {
      http.send(JSON.stringify(params))
    }
  })
}
